<!--
 * @Author: your name
 * @Date: 2020-08-04 17:05:51
 * @LastEditTime: 2021-09-28 21:30:57
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \MWZ_MIS\src\components\MonthRangeInput.vue
-->
<template>
  <q-input
    v-model="formatTime"
    filled
    mask="###### - ######"
    :label="field.label"
    @click="popProxy"
  >
    <template v-slot:append>
      <q-icon
        name="event"
        class="cursor-pointer"
      >
        <q-popup-proxy
          ref="qMonthProxy"
          transition-show="scale"
          transition-hide="scale"
          v-model="proxyShown"
        >
          <monthpicker color="primary" v-model="selectMonth" @change="change" />
        </q-popup-proxy>
      </q-icon>
    </template>
  </q-input>
</template>
<script>
import { defineComponent } from 'vue';
import { date } from 'quasar';
import monthpicker from 'src/components/MonthPicker.vue';

export default defineComponent({
  name: 'monthrangeinput',
  components: {
    monthpicker
  },
  props: {
    field: {
      type: Object,
      default: () => {}
    }
  },
  data () {
    const self = this;
    return {
      proxyShown: false,
      begin: '',
      end: '',
      selectMonth: '',
      clickCount: 0
    }
  },
  methods: {
    change (val) {
      if (this.proxyShown) {
        if (this.clickCount == 0) {
          this.begin = val;
          this.field.value = `${val}|`
          this.clickCount++;
        } else {
          this.end = val;
          this.field.value = this.begin > this.end ? `${this.end}|${this.begin}` : `${this.begin}|${this.end}`;
          this.$refs.qMonthProxy.hide();
          this.clickCount = 0;
        }
      }
    },
    popProxy () {
      this.$refs.qMonthProxy.show();
    }
  },
  computed: {
    formatTime: {
      get () {
        if (this.field.value && this.field.value.indexOf('|')) {
          return this.field.value.replace(/\|/, ' - ');
        } else {
          return '';
        }
      },
      set (val) {
        if (val.length === 15) {
          this.field.value = val.split(' - ').join('|');
        }
      }
    }
  },
  watch: {
    /* selectMonth (val) {
      if (this.proxyShown) {
        if (this.clickCount == 0) {
          this.begin = val;
          this.field.value = `${val}|`
          this.clickCount++;
        } else {
          this.end = val;
          this.field.value = this.begin > this.end ? `${this.end}|${this.begin}` : `${this.begin}|${this.end}`;
          this.$refs.qMonthProxy.hide();
          this.clickCount = 0;
        }
      }
    } */
  },
  mounted () {
    if (this.field.months > 0) {
      const end = date.formatDate(Date.now(), 'YYYYMM');
      const beginDate = new Date();
      beginDate.setMonth(beginDate.getMonth() - this.field.months);
      const begin = date.formatDate(beginDate, 'YYYYMM');
      this.field.value = `${begin}|${end}`;
      this.selectMonth = begin;
    }
  }
});
</script>
